package com.fuli.app.service.Serviceimpl;

import com.fuli.app.common.ActionResult;
import com.fuli.app.common.Pagination;
import com.fuli.app.common.SystemContext;
import com.fuli.app.dao.CurriculumCategoryDao;
import com.fuli.app.dao.CurriculumDao;
import com.fuli.app.dto.CurriculumDTO;
import com.fuli.app.dto.query.CurriculumQueryDTO;
import com.fuli.app.entity.Curriculum;
import com.fuli.app.entity.CurriculumCategory;
import com.fuli.app.service.CurriculumService;
import com.fuli.app.util.AliYunUtils;
import com.fuli.app.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CurriculumServiceImpl implements CurriculumService {
    @Autowired
    private CurriculumDao curriculumDao;
    @Autowired
    private CurriculumCategoryDao curriculumCategoryDao;

    @Override
    public ActionResult<CurriculumDTO> get(String id) {
        Curriculum curriculum = curriculumDao.get(id);
        CurriculumDTO curriculumDTO = EntityUtils.copyObject(curriculum, CurriculumDTO.class);
        return new ActionResult<>(curriculumDTO);
    }

    @Override
    public ActionResult<String> up(String id) {
        Curriculum po = curriculumDao.get(id);
        if (po == null)
            return new ActionResult<>(-1, "升序失败，不存在id=" + id + "的数据");
        List<Curriculum> poList = curriculumDao.listAllByCategoryId(po.getCategoryId());
        if (CollectionUtils.isEmpty(poList))
            return new ActionResult<>(-1, "升序失败，不存在同级数据");
        for (int i = 0; i < poList.size(); i++) {
            if (id.equals(poList.get(i).getId()) && i != 0) {
                poList.set(i, poList.get(i - 1));
                poList.set(i - 1, po);
                break;
            }
        }
        //重新设置排序
        for (int i = 0; i < poList.size(); i++) {
            poList.get(i).setSortIndex(i);
        }
        curriculumDao.batchUpdateSortIndex(poList, SystemContext.getUserId());
        return new ActionResult<>(id);
    }

    @Override
    public ActionResult<String> down(String id) {
        Curriculum po = curriculumDao.get(id);
        if (po == null)
            return new ActionResult<>(-1, "降序失败，不存在id=" + id + "的数据");
        List<Curriculum> poList = curriculumDao.listAllByCategoryId(po.getCategoryId());
        if (CollectionUtils.isEmpty(poList))
            return new ActionResult<>(-1, "降序失败，不存在同级数据");
        for (int i = 0; i < poList.size(); i++) {
            if (id.equals(poList.get(i).getId()) && i != (poList.size() - 1)) {
                poList.set(i, poList.get(i + 1));
                poList.set(i + 1, po);
                break;
            }
        }
        //重新设置排序
        for (int i = 0; i < poList.size(); i++) {
            poList.get(i).setSortIndex(i);
        }
        curriculumDao.batchUpdateSortIndex(poList, SystemContext.getUserId());
        return new ActionResult<>(id);
    }

    @Override
    public ActionResult<String> refresh(String categoryId) {
        List<Curriculum> poList = curriculumDao.listAllByCategoryId(categoryId);
        if (CollectionUtils.isEmpty(poList))
            return new ActionResult<>(-1, "降序失败，不存在同级数据");
        //重新设置排序
        for (int i = 0; i < poList.size(); i++) {
            poList.get(i).setSortIndex(i);
        }
        curriculumDao.batchUpdateSortIndex(poList, SystemContext.getUserId());
        return new ActionResult<>(categoryId);
    }

    @Override
    public ActionResult<Pagination<CurriculumDTO>> listByQueryDTO(CurriculumQueryDTO queryDTO) {
        Pagination<CurriculumDTO> pagination = new Pagination<>(queryDTO.getPageNo(), queryDTO.getPageSize());
        int count = curriculumDao.countByQueryDTO(queryDTO);
        pagination.setCount(count);
        if (count > 0) {
            List<Curriculum> poList = curriculumDao.listByQueryDTO(queryDTO);
            List<CurriculumDTO> dtoList = EntityUtils.copyList(poList, CurriculumDTO.class);
            pagination.setRows(dtoList);
        }
        return new ActionResult<>(pagination);
    }


    @Override
    public ActionResult<String> delete(String id) {
        Curriculum curriculum = curriculumDao.get(id);
        if (curriculum == null)
            return new ActionResult<>(id);
        curriculumDao.delete(id, SystemContext.getUserId());
        //删除阿里云视频
        // 接口私有参数列表, 不同API请替换相应参数
        Map<String, String> privateParams = new HashMap<>();
        // 视频ID
        privateParams.put("VideoIds", curriculum.getVideoId());
        // API名称
        privateParams.put("Action", "DeleteVideo");

        // 接口公有参数列表, 不同API请替换相应参数
        Map<String, String> publicParams = new HashMap<>();
        publicParams.put("Format", "JSON");
        publicParams.put("Version", "2017-03-21");
        publicParams.put("AccessKeyId", AliYunUtils.access_key_id);
        publicParams.put("SignatureMethod", "HMAC-SHA1");
        publicParams.put("Timestamp", AliYunUtils.generateTimestamp());
        publicParams.put("SignatureVersion", "1.0");
        publicParams.put("SignatureNonce", AliYunUtils.generateRandom());
        if (AliYunUtils.security_token != null && AliYunUtils.security_token.length() > 0) {
            publicParams.put("SecurityToken", AliYunUtils.security_token);
        }
        String URL = null;
        try {
            URL = AliYunUtils.generateOpenAPIURL(publicParams, privateParams);
            try {
                AliYunUtils.httpGet(URL);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new ActionResult<>(URL);
    }

    @Override
    public ActionResult<String> batchDelete(List<String> ids) {
        List<Curriculum> curriculumList = curriculumDao.getList(ids);
        String videoIds = "";
        for (int i = 0; i < curriculumList.size(); i++) {
            if (videoIds.length() == 0) {
                videoIds = videoIds + curriculumList.get(i).getVideoId();
            } else {
                videoIds = videoIds + "," + curriculumList.get(i).getVideoId();
            }
        }

        curriculumDao.batchDelete(ids, SystemContext.getUserId());

        //删除阿里云视频
        // 接口私有参数列表, 不同API请替换相应参数
        Map<String, String> privateParams = new HashMap<>();
        // 视频ID
        privateParams.put("VideoId", videoIds);
        // API名称
        privateParams.put("Action", "DeleteVideo");

        // 接口公有参数列表, 不同API请替换相应参数
        Map<String, String> publicParams = new HashMap<>();
        publicParams.put("Format", "JSON");
        publicParams.put("Version", "2017-03-21");
        publicParams.put("AccessKeyId", AliYunUtils.access_key_id);
        publicParams.put("SignatureMethod", "HMAC-SHA1");
        publicParams.put("Timestamp", AliYunUtils.generateTimestamp());
        publicParams.put("SignatureVersion", "1.0");
        publicParams.put("SignatureNonce", AliYunUtils.generateRandom());
        if (AliYunUtils.security_token != null && AliYunUtils.security_token.length() > 0) {
            publicParams.put("SecurityToken", AliYunUtils.security_token);
        }
        String URL = null;
        try {
            URL = AliYunUtils.generateOpenAPIURL(publicParams, privateParams);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new ActionResult<>(URL);

    }

    @Override
    public ActionResult<String> add(String file, String name, String notice, String categoryId, String intro) {


        Curriculum po = EntityUtils.init(Curriculum.class);
        //region 验证分类是否存在和是否叶子节点，无分类即categoryId=root跳过
        if (!"root".equals(categoryId)) {
            CurriculumCategory curriculumCategory = curriculumCategoryDao.get(categoryId);
            if (curriculumCategory == null)
                return new ActionResult<>(-1, "案例分类不存在，categoryId=" + categoryId);
//            if (curriculumCategory.getLeaf())
//                return new ActionResult<>(-1, "案例分类是叶子节点，categoryId=" + categoryId);
        }
        String videoId = AliYunUtils.UploadVideo(AliYunUtils.access_key_id, AliYunUtils.access_key_secret, name, file);
        if (videoId == null)
            return new ActionResult<>(-1, "文件上传失败");
        po.setVideoId(videoId);
        po.setNotice(notice);
        po.setCategoryId(categoryId);
        po.setIntro(intro);
        po.setName(name);
        Integer max = curriculumDao.getMaxSortIndex(po.getCategoryId());
        max = max == null ? 0 : max + 1;
        po.setSortIndex(max);
        //endregion
        curriculumDao.insert(po);
        return new ActionResult<>(po.getId());
    }

    @Override
    public ActionResult<String> update(CurriculumDTO dto) {
        Curriculum po = curriculumDao.get(dto.getId());
        if (po == null)
            return new ActionResult<>(-1, "修改失败，不存在id=" + dto.getId() + "的数据");
        //region 验证分类是否存在和是否叶子节点，无分类即categoryId=root跳过
        if (!po.getCategoryId().equals(dto.getCategoryId())) {
            if (!"root".equals(dto.getCategoryId())) {
                CurriculumCategory curriculumCategory = curriculumCategoryDao.get(dto.getCategoryId());
                if (curriculumCategory == null)
                    return new ActionResult<>(-1, "案例分类不存在，categoryId=" + dto.getCategoryId());
//                if (!curriculumCategory.getLeaf())
//                    return new ActionResult<>(-1, "案例分类不是叶子节点，categoryId=" + dto.getCategoryId());
                Integer max = curriculumDao.getMaxSortIndex(dto.getCategoryId());
                max = max == null ? 0 : max + 1;
                po.setSortIndex(max);
            }
        }
        //endregion
        po.setUpdateId(SystemContext.getUserId());
        po.setName(dto.getName());
        po.setIntro(dto.getIntro());
        po.setNotice(dto.getNotice());
        curriculumDao.update(po);
        return new ActionResult<>(po.getId());
    }
}
